package com.piece.mall.controller;

import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.constant.FrameWorkConstants;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.support.response.Select;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.file.ImageUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.file.client.FileClientFactory;
import com.piece.file.model.TbSysFile;
import com.piece.file.service.TbSysFileService;
import com.piece.mall.model.SmsCoupon;
import com.piece.mall.service.SmsCouponService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Api(tags = {"优惠券管理"})
@RequestMapping("/api/mall/coupon")
public class SmsCouponController extends FrameWorkController {

    @Resource
    private SmsCouponService smsCouponService;

    @Resource
    private TbSysFileService tbSysFileService;

    @Autowired
    private FileClientFactory fileClientFactory;

    @PostMapping("/list")
    @AclPermission(code = "mall:coupon:view")
    @ApiOperation(value = "查询优惠券列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = smsCouponService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "mall:coupon:view")
    @ApiOperation(value = "查询优惠券分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = smsCouponService.findPage(queryTable);
        return success(dataTable);
    }

    @PostMapping("/query/select")
    @ApiOperation(value = "查询优惠券下拉列表")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "分页查询条件", dataTypeClass = Select.class, type = "body")
    })
    public AjaxResponse selectCustomQuery() {
        String selected = getRequest().getParameter("selected");
        QueryTable queryTable = initSelect("Q_couponName_S_LK");
        Map<String, Object> param = queryTable.getParams();
        param.put("sort", 1);
        queryTable.setParams(param);
        DataTable dataTable = smsCouponService.findPage(queryTable);
        if (StringUtil.isNotEmpty(selected)) {
            selected = FrameWorkConstants.SPLIT_PARAM + selected + FrameWorkConstants.SPLIT_PARAM;
        }
        return success(tableToSelect(dataTable, selected));
    }

    private Select tableToSelect(DataTable dataTable, String selected) {
        Select select = Select.builder().build();
        List<Object> tableData = dataTable.getData();
        List<Select.Entity> entityList = tableData.stream().map(data -> {
            SmsCoupon coupon = (SmsCoupon) data;
            return select.new Entity(Convert.toStr(coupon.getId()), Convert.toStr(coupon.getCouponName()));
        }).filter(entity -> {
            if (StringUtil.isNotEmpty(selected)) {
                if (selected.indexOf(FrameWorkConstants.SPLIT_PARAM + entity.getId() + FrameWorkConstants.SPLIT_PARAM) != -1) {
                    return true;
                }
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        select.setTotal(dataTable.getRecordsTotal());
        select.setData(entityList);
        return select;
    }

    @GetMapping("/load")
    @AclPermission(code = "mall:coupon:view")
    @ApiOperation(value = "加载优惠券表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        long id = Convert.toLong(getRequest().getParameter("id"), 0L);
        SmsCoupon smsCoupon = new SmsCoupon();
        if (id != 0) {
            smsCoupon = smsCouponService.findById(id);
        }
        return success(smsCoupon);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "mall:coupon:edit")
    @ApiOperation(value = "保存优惠券表单数据")
    @ApiImplicitParam(value = "优惠券数据", dataTypeClass = SmsCoupon.class, type = "body")
    public AjaxResponse save() {
        SmsCoupon smsCoupon;
        try {
            Long id = Convert.toLong(getRequest().getParameter("id"));
            if (null != id) {
                smsCoupon = smsCouponService.findById(id);
            } else {
                smsCoupon = new SmsCoupon();
            }
            initDB(smsCoupon);
            smsCouponService.insertOrUpdate(smsCoupon);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/uploadThumbnailFinal")
    @ApiOperation(value = "上传缩略图")
    @ApiImplicitParam(name = "avatar_file", value = "缩略图")
    public AjaxResponse uploadThumbnailFinal(@RequestParam("avatar_file") MultipartFile file) {
        if (file != null) {
            InputStream is = null;
            try {
                is = file.getInputStream();
                byte[] bytes = ImageUtil.scale(is, 1024);
                TbSysFile sysFile = fileClientFactory.get().writeToStore(bytes, "thumbnail", file.getOriginalFilename(), file.getSize());
                return success(sysFile.getFileId());
            } catch (Exception e) {
                return error(I18nUtil.message(ExceptionConstants.UPLOAD_ERROR), e.getMessage());
            }
        }
        return error(I18nUtil.message(ExceptionConstants.NO_SELECT));
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "mall:coupon")
    @ApiOperation(value = "删除优惠券数据")
    @ApiImplicitParam(name = "id", value = "主键", type = "path")
    public AjaxResponse delete(@PathVariable String id) throws Exception {
        smsCouponService.delete(id);
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "mall:coupon")
    @ApiOperation(value = "删除优惠券数据")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse deleteBatch() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            smsCouponService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }
}
